<template>
  <div class="eidt">
    <hmNanBar
      :title="title[type]"
      :right="right"
      :path="path"
      @rightClick="seva"
    ></hmNanBar>
    <div class="_input">
      <van-field v-if="type !== 'avatar'" v-model="inputvalue" class="field" />
      <van-uploader
        v-else
        :before-read="beforeRead"
        :after-read="afterRead"
        :before-delete="del"
        v-model="fileList"
        :max-count="1"
      />
    </div>
  </div>
</template>

<script>
// 引入vuex用户信息
import { mapState } from 'vuex'
// 引入修改用户资料的接口// 引入上传图片接口
import { auEdit, upLoad } from '@/api/my.js'
export default {
  data () {
    return {
      inputvalue: '',
      right: '',
      path: '/home/myinfo',
      type: this.$route.query.type,
      title: {
        nickname: '修改昵称',
        intro: '修改个人简介',
        avatar: '修改头像',
        position: '修改岗位'
      },
      fileList: []
    }
  },
  //   展开用户资料
  computed: {
    ...mapState(['userInfo'])
  },
  created () {
    if (this.type === 'position') {
      this.path = '/home/my'
    }
    if (this.type === 'avatar') {
      if (this.userInfo[this.type]) {
        this.fileList[0] = {
          url: process.env.VUE_APP_URL + this.userInfo[this.type]
        }
      }
    } else {
      // 将地址传参过来的值赋值给输入框
      this.inputvalue = this.userInfo[this.type]
    }
  },
  // 事件监听 查看输入框中newVal修改前的值是否等于修改后的值或者为空 取反后满足条件显示保存否则为空
  watch: {
    inputvalue (newVal) {
      if (newVal !== this.userInfo[this.type] && newVal !== '') {
        this.right = '保存'
      } else {
        this.right = ''
      }
    }
  },
  methods: {
    // 加一个判断条件 当right为空时不执行下面保存代码
    seva () {
      if (this.right === '') {
        return
      }
      if (this.inputvalue) {
        this.eidtInfo()
      }
    },
    eidtInfo (value) {
      auEdit({
        [this.type]: this.inputvalue
      }).then(() => {
        this.$toast.success('修改成功')
        this.$store.dispatch('getUserIndo')
        this.$router.push(this.path)
      })
    },
    // 文件上传前的判断
    beforeRead (files) {
      const isImg = files.type === 'image/png'
      const limit1M = files.size / 1024 / 1024 < 1
      if (!isImg) {
        this.$toast.fail('请上传image/png格式图片')
      }
      if (!limit1M) {
        this.$toast.fail('请上传小于1M的图片')
      }
      return isImg && limit1M
    },
    // 图片上传后
    afterRead (res) {
      console.log(res)
      const _formData = new FormData()
      _formData.append('files', res.file)
      this.fileList[0].status = 'uploading'
      upLoad(_formData).then(res1 => {
        this.inputvalue = res1.data.data[0].id
        this.fileList[0].status = 'done'
      })
    },
    del () {
      this.inputvalue = ''
      return true
    }
  }
}
</script>

<style lang="less" scoped>
._input {
  padding: 20px @p15;
  .field {
    width: 345px;
    height: 34px;
    background: #f7f4f5;
    border-radius: 8px;
  }
}
</style>
